package hservice

import (
	"encoding/base64"
	"encoding/hex"
	"fmt"
	"math/rand"
	"strings"
	"time"

	"advertoper/db"
	"advertoper/errorcode"

	"doubimeizhi.com/datatable"
	"doubimeizhi.com/utility"

	"github.com/astaxie/beego"
	log "github.com/cihub/seelog"
)

var (
	defaultTemporaryPassportService *TemporaryPassportService
)

type TemporaryPassportService struct {
}

func newTemporaryPassportService() *TemporaryPassportService {
	service := &TemporaryPassportService{}
	return service
}

func GetTemporaryPassportService() *TemporaryPassportService {
	if defaultTemporaryPassportService == nil {
		defaultTemporaryPassportService = &TemporaryPassportService{}
	}
	return defaultTemporaryPassportService
}

//查询返回数据
type PassportCheckReq struct {
	Vuid string
}

type PassportCheckResp struct {
	Code     uint
	Msg      string
	IsRegist int
	Uid      string
	Avatar   string
	NickName string
}

//客户端来查询临时账号是否存在
func (p *TemporaryPassportService) PassportCheck(req *PassportCheckReq, resp *PassportCheckResp) error {
	if req.Vuid == "" {
		resp.Code = 101
		resp.Msg = "vuid不能为空"
		return nil
	}
	//得到base64之后的vuid
	end_vuid := p.base64Encode(req.Vuid)
	//加上标识
	end_vuid = fmt.Sprintf("ZJ-%s", end_vuid)
	//去数据库查询
	daq := datatable.NewDataTableQuery()
	daq.SetTableName("temporary_passport")
	daq.PushField(&datatable.FiledItem{Alias: "num", Field: "count(0)"})
	daq.PushCondition("vuid = ?", end_vuid)

	sql, values := daq.GenerateSQL()
	mysqlHelper := db.GetHomePageInfoMysqlHelper()
	results, err := mysqlHelper.Query(sql, values...)
	if err != nil {
		log.Errorf("query vuid fail ,~~~PassportCheck(),err is %s", err.Error())
		resp.Code = errorcode.EC_GL_INTERNAL_ERROR
		resp.Msg = errorcode.Msg(errorcode.EC_GL_INTERNAL_ERROR)
		return nil
	}
	num := mysqlHelper.GetColInt(results[0], "num")
	if num > 0 {
		resp.Code = errorcode.EC_GL_SUCCESS
		resp.Msg = errorcode.Msg(errorcode.EC_GL_SUCCESS)
		resp.IsRegist = 1
		return nil
	}
	//不存在，添加一条数据
	nowTick := time.Now().Unix()
	data := make(map[string]*utility.MySQLFieldValue)
	data["vuid"] = utility.NewMySQLFieldValue(end_vuid, false)
	data["uid"] = utility.NewMySQLFieldValue("", false)
	data["insert_tick"] = utility.NewMySQLFieldValue(nowTick, false)
	mysqlHelper2 := db.GetHomePageInfoMysqlHelper()
	_, err2 := mysqlHelper2.SaveRecord(data, "temporary_passport")
	if err2 != nil {
		log.Errorf("insert new vuid fail ,~~~PassportCheck,err is %s", err2.Error())
		resp.Code = errorcode.EC_GL_INTERNAL_ERROR
		resp.Msg = errorcode.Msg(errorcode.EC_GL_INTERNAL_ERROR)
		return nil
	}
	//得到默认的昵称和图像
	nickName := fmt.Sprintf("ZJ-%s", req.Vuid[len(req.Vuid)-6:len(req.Vuid)])
	avatarBaseURL := beego.AppConfig.DefaultString("avatarURL", "http://www.zhijianyaokong.com/zj_avatar/")
	a_Numeber := beego.AppConfig.DefaultInt("avatarURLNum", 40)
	rand.Seed(nowTick)
	number := rand.Intn(a_Numeber) + 1
	avatar := fmt.Sprintf("%s%d.jpg", avatarBaseURL, number)

	resp.Code = errorcode.EC_GL_SUCCESS
	resp.Msg = errorcode.Msg(errorcode.EC_GL_SUCCESS)
	resp.IsRegist = 2
	resp.NickName = nickName
	resp.Uid = end_vuid
	resp.Avatar = avatar

	return nil

}

//登陆，注册成功上报
func (p *TemporaryPassportService) LoginUpload(vuid, uid string) (uint, string) {
	if vuid == "" || uid == "" {
		return 101, "vuid or uid can not be empty"
	}
	//得到base64之后的vuid
	end_vuid := p.base64Encode(vuid)
	//加上标识
	end_vuid = fmt.Sprintf("ZJ-%s", end_vuid)
	//查询是否有匹配的vuid和uid
	daq := datatable.NewDataTableQuery()
	daq.SetTableName("temporary_passport")
	daq.PushField(&datatable.FiledItem{Alias: "num", Field: "count(0)"})
	daq.PushCondition("vuid = ?", end_vuid)
	daq.PushCondition("uid = ?", uid)
	sql, values := daq.GenerateSQL()
	mysqlHelper := db.GetHomePageInfoMysqlHelper()
	results, err := mysqlHelper.Query(sql, values...)
	if err != nil {
		log.Errorf("query vuid and uid fail ,~~~LoginUpload(),err is %s", err.Error())
		return errorcode.EC_GL_INTERNAL_ERROR, errorcode.Msg(errorcode.EC_GL_INTERNAL_ERROR)
	}
	num := mysqlHelper.GetColInt(results[0], "num")
	if num > 0 {
		//存在，直接返回
		return errorcode.EC_GL_SUCCESS, errorcode.Msg(errorcode.EC_GL_SUCCESS)
	}
	//不存在，插入一条新数据
	data := make(map[string]*utility.MySQLFieldValue)
	data["vuid"] = utility.NewMySQLFieldValue(end_vuid, false)
	data["uid"] = utility.NewMySQLFieldValue(uid, false)
	data["insert_tick"] = utility.NewMySQLFieldValue(time.Now().Unix(), false)
	mysqlHelper2 := db.GetHomePageInfoMysqlHelper()
	_, err2 := mysqlHelper2.SaveRecord(data, "temporary_passport")
	if err2 != nil {
		log.Errorf("insert new vuid and uid fail ,~~~LoginUpload,err is %s", err2.Error())
		return errorcode.EC_GL_INTERNAL_ERROR, errorcode.Msg(errorcode.EC_GL_INTERNAL_ERROR)
	}
	//更新其中临时账号状态
	go p.updateTemporaryPassport(end_vuid)

	return errorcode.EC_GL_SUCCESS, errorcode.Msg(errorcode.EC_GL_SUCCESS)

}

//将Vuid经过base64之后返回
func (p *TemporaryPassportService) base64Encode(vuid string) string {
	//将vuid的'-'去掉
	vuid2 := strings.Replace(vuid, "-", "", -1)
	//将其中字母全换成小写
	vuid3 := strings.ToLower(vuid2)
	//将其转换为[]byte，32字符变成16字节
	str_byte := make([]byte, 0)
	for i := 0; i < len(vuid3); i += 2 {
		b, _ := hex.DecodeString(vuid3[i : i+2])
		str_byte = append(str_byte, b[0])
	}
	//做base64
	u_vuid := base64.URLEncoding.EncodeToString(str_byte)
	//将其等号去掉
	end_vuid := strings.Replace(u_vuid, "=", "", -1)
	return end_vuid
}

//将base64之后的数据还原
func (p *TemporaryPassportService) base64Decode(end_vuid string) string {
	//对其加上之前去掉的'='
	n := len(end_vuid) % 4
	k := 0
	if n == 2 || n == 3 {
		k = 4 - n
	}
	for i := 0; i < k; i++ {
		end_vuid = fmt.Sprintf("%s%s", end_vuid, "=")
	}
	//反向base64
	b, _ := base64.URLEncoding.DecodeString(end_vuid)
	vuid := hex.EncodeToString(b)
	return vuid
}

//更新临时账号状态
func (p *TemporaryPassportService) updateTemporaryPassport(end_vuid string) {
	updaq := datatable.NewDataTableUpdate()
	updaq.SetTableName("temporary_passport")
	updaq.SetUpdateValue("status=?", 1)
	updaq.PushCondition("vuid=?", end_vuid)
	updaq.PushCondition("uid=?", "")
	sql, values := updaq.GenerateSQL()
	mysqlHelper := db.GetHomePageInfoMysqlHelper()
	_, err2 := mysqlHelper.Exec(sql, values...)
	if err2 != nil {
		log.Errorf("update tem_passport status fail ,~~~updateTemporaryPassport,err is %s", err2.Error())
	}
}
